package com.fenrirtec.aepp.manage.api;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.UserDto;
import com.fenrirtec.aepp.common.service.SystemConfigService;
import com.fenrirtec.aepp.common.service.UserManageService;
import com.fenrirtec.aepp.common.service.impl.SystemConfigServiceImpl;
import com.fenrirtec.aepp.common.service.impl.UserManageServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.aepp.manage.common.definition.Definition;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.definition.BaseDefinition.API.Common;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.DigestUtils;

public class ChangePasswordAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(ChangePasswordAPI.class);

	public ChangePasswordAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		SystemConfigService systemConfigService = new SystemConfigServiceImpl();
		UserManageService loginService = new UserManageServiceImpl();
		boolean result = false;
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			String loginName = jsonObj.getString("login_name");
			String loginPassword = jsonObj.getString("login_password");
			String newPassword = jsonObj.getString("new_password");
			
			if (loginName.equalsIgnoreCase(Definition.ADMIN)) {
				if (DigestUtils.SHAHashing(loginPassword).equals(getSystemConfig().getPassword())) {
					result = systemConfigService.changePassword(loginName, DigestUtils.SHAHashing(newPassword));
				}
			} else {
				UserDto userDto = loginService.login(loginName, loginPassword);
				if (userDto != null && userDto.getLoginPassword().equals(DigestUtils.SHAHashing(loginPassword))) {
					result = systemConfigService.changePassword(userDto.getLoginName(), DigestUtils.SHAHashing(newPassword));
				}
			}
			
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		JSONObject root = new JSONObject();
		root.put(Common.Response.RESULT, result);
		return root;
	}
}
